package cn.leftsite.juc.pattern.nio;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.LockSupport;

/**
 * @author wangjinqiang
 * @date 2019-06-06
 */
public class HeavySocketClient {
    private static ExecutorService tp = Executors.newCachedThreadPool();
    private static final int SLEEP_TIME = 1000_000_000;

    public static class EchoClient implements Runnable {

        @Override
        public void run() {
            try (Socket client = new Socket("127.0.0.1", 8000);
                 PrintWriter writer = new PrintWriter(client.getOutputStream(),true);
                 BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()))) {
                writer.println("H");
                LockSupport.parkNanos(SLEEP_TIME);
                writer.println("E");
                LockSupport.parkNanos(SLEEP_TIME);
                writer.println("L");
                LockSupport.parkNanos(SLEEP_TIME);
                writer.println("L");
                LockSupport.parkNanos(SLEEP_TIME);
                writer.println("O");
                LockSupport.parkNanos(SLEEP_TIME);
                writer.println("!");
                LockSupport.parkNanos(SLEEP_TIME);

                System.out.println("from server: "+reader.readLine());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        EchoClient ec = new EchoClient();
        for (int i = 0; i < 10; i++) {
            tp.execute(ec);
        }
    }

}
